<template>
  <div class="postPublish">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="javascript:;">文章管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>文章发布</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card
      class="box-card"
      style="margin-top:20px;"
    >
      <!-- 主要内容 -->
      <el-form
        ref="form"
        :model="postForm"
        label-width="80px"
      >
        <!-- 便签栏 -->
        <el-form-item label="标签">
          <el-input v-model="postForm.title"></el-input>
        </el-form-item>
        <!-- 类型栏 -->
        <el-form-item label="类型">
          <el-radio-group v-model="postForm.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 内容栏 -->
        <el-form-item label="内容">
          <VueEditor
            :config="config"
            ref="vueEditor"
            v-if="postForm.type == 1"
          />
          <el-upload
            class="upload-demo"
            :headers="getToken()"
            v-if="postForm.type == 2"
            :on-success="onsuccess"
            :before-upload="beforeupload"
            :action="baseURL + '/upload'"
            :file-list="fileList"
          >
            <el-button
              size="small"
              type="primary"
            >点击上传</el-button>
          </el-upload>
        </el-form-item>
        <!-- 栏目栏 -->
        <el-form-item label="栏目">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(v,i) in catelist"
              :label="v.id"
              :key="i"
            >{{v.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 封面栏 -->
        <el-form-item label="封面">
          <el-upload
            :action="baseURL + '/upload'"
            :headers="getToken()"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handlerPoster"
            :file-list="postForm.cover"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img
              width="100%"
              :src="dialogImageUrl"
              alt=""
            />
          </el-dialog>
        </el-form-item>
        <!-- 发表文章按钮 -->
        <el-button
          type="primary"
          @click.native="publishPost"
        >发布文章</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { category, sendPost, postData, editPost } from "@/api/post.js";
import axios from "@/utils/myaxios.js";
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
export default {
  data() {
    return {
      catelist: [], // 获得的栏目数据的数组
      checkAll: false, // 是否全选
      checkedCities: [], // 选中添加的数组
      isIndeterminate: false, // 是否全选

      dialogVisible: false,
      dialogImageUrl: "",
      fileList: [],
      baseURL: axios.defaults.baseURL,
      postForm: {
        title: "", // 标题
        content: "", // 内容
        categories: [], // 栏目分类
        cover: [], // 封面
        type: 1, // 类型
      },
      config: {
        // 上传图片的配置
        uploadImage: {
          url: axios.defaults.baseURL + "/upload",
          headers: this.getToken,
          name: "file",
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert(axios.defaults.baseURL + res.data.data.url);
          },
        },

        // 上传视频的配置
        uploadVideo: {
          url: axios.defaults.baseURL + "/upload",
          headers: this.getToken,
          name: "file",
          uploadSuccess(res, insert) {
            insert(axios.defaults.baseURL + res.data.data.url);
          },
        },
      },
    };
  },
  components: {
    VueEditor,
  },
  methods: {
    // 单击全选
    handleCheckAllChange(val) {
      this.checkedCities = val
        ? this.catelist.map((v) => {
            return v.id;
          })
        : [];
      this.isIndeterminate = false;
    },
    // 点击复选项
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.catelist.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.catelist.length;
    },
    getToken() {
      return {
        Authorization: JSON.parse(localStorage.getItem("hm_houtai_toutai"))
          .token,
      };
    },
    async publishPost() {
      if (this.postForm.type == 1) {
        this.postForm.content = this.$refs.vueEditor.editor.root.innerHTML;
      }
      this.postForm.categories = this.checkedCities.map((v) => {
        return { id: v };
      });
      if (this.postForm.title.trim() == "") {
        this.$message.warning("标题不能为空");
        return;
      }
      if (this.postForm.content.trim() == "") {
        this.$message.warning("内容不能为空");
        return;
      }
      if (this.postForm.categories.length == 0) {
        this.$message.warning("至少选一个分类");
        return;
      }
      if (this.postForm.cover.length == 0) {
        this.$message.warning("至少上传一个封面");
        return;
      }
      if (this.$route.params.id) {
        let res = await editPost(this.$route.params.id, this.postForm);
        if (res.data.message == "文章编辑成功") {
          this.$message.success(res.data.message);
          this.$router.push({ name: "postlist" });
        } else {
          this.$message.error(res.data.message);
        }
      } else {
        let res = await sendPost(this.postForm);
        if (res.data.message == "文章发布成功") {
          this.$message.success(res.data.message);
          this.$router.push({ name: "postlist" });
        } else {
          this.$message.error(res.data.message);
        }
      }
    },
    onsuccess(response) {
      if (response.message == "文件上传成功") {
        this.postForm.content = this.baseURL + response.data.url;
      }
    },
    beforeupload(file) {
      if (file.type != "video/avi") {
        this.$message({
          type: "error",
          message: "类型不对",
        });
        return false;
      } else if (file.size / 1024 / 1024 > 8) {
        this.$message({
          type: "error",
          message: "文件过大",
        });
        return false;
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
    handleRemove(file) {
      let id = file.response.data.id;
      console.log(id);
      for (let i = 0; i < this.postForm.cover.length; i++) {
        if (this.postForm.cover[i].id == id) {
          this.postForm.cover.splice(i, 1);
          break;
        }
      }
    },
    handlerPoster(response) {
      this.postForm.cover.push({
        id: response.data.id,
        url: this.baseURL + response.data.url,
      });
    },
    handleExceed() {
      this.$message({
        type: "error",
        message: "最多只能上传3张图片",
      });
    },
  },
  async mounted() {
    let res = await category();
    this.catelist = res.data.data.splice(1);
    let id = this.$route.params.id;
    if (id) {
      console.log(id);
      let res = (await postData(id)).data.data;
      console.log(res);
      this.postForm.title = res.title;
      this.postForm.type = res.type;
      this.$refs.vueEditor.editor.clipboard.dangerouslyPasteHTML(
        0,
        res.content
      );
      this.checkedCities = res.categories.map((v) => {
        return v.id;
      });
      this.postForm.cover = res.cover.map((v) => {
        if (v.url.indexOf("http") == -1) {
          v.url = this.baseURL + v.url;
        }
        return v;
      });
    }
  },
};
</script>

<style></style>
